package com.aquila.bible.activity;

import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.Html;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.aquila.bible.MyBaseActivity;
import com.aquila.bible.R;
import com.aquila.bible.SearchResultObject;
import com.aquila.bible.sqlite.CollectionSqlite;
import com.aquila.bible.system.SystemConfig;
import com.umeng.analytics.MobclickAgent;

public class CollectionActivity extends MyBaseActivity {
	
	private ArrayList<SearchResultObject> arrayList = new ArrayList<SearchResultObject>() ;
	private ListView listView ;
	private CollectionAdapter adapter ;
	private TextView nullPromptTextView ;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_collection) ;
		listView = (ListView) findViewById(R.id.lv_collection) ;
		nullPromptTextView = (TextView) findViewById(R.id.tv_null_prompt) ;
		MobclickAgent.onEvent(this, "5") ;
	}
	
	@Override
	protected void onStart() {
		super.onStart();
		initData() ; // 初始化加载数据
	}
	
	private void initData(){
		CollectionSqlite sqlite = new CollectionSqlite(context) ;
		sqlite.open() ;
		arrayList = sqlite.getAllData() ;
		sqlite.close() ;
		if (arrayList == null || arrayList.size() == 0) {
        	nullPromptTextView.setVisibility(View.VISIBLE) ;
        }
		else {
			nullPromptTextView.setVisibility(View.GONE) ;
			if (SystemConfig.sp.getBoolean("showCollectionPrompt", true)) {
            	showPrompr() ;
            }
			init() ;
		}
		
	}
	
	private void showPrompr(){
		Builder builder = new Builder(context);
		builder.setTitle("操作提示")
		.setMessage("点击经文可直接进入阅读，长按经文可选择删除")
		.setPositiveButton("不再提醒", new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				SystemConfig.editor.putBoolean("showCollectionPrompt", false) ;
				SystemConfig.editor.commit() ;
				dialog.dismiss() ;
			}
		})
		.setNegativeButton("我知道了", null)
		.create().show() ;
	}
	
	/**
	 * 
	 *Administrator
	 *2012-8-8 下午9:03:34
	 */
	private void init(){
		adapter = new CollectionAdapter() ;
		listView.setAdapter(adapter) ;
		listView.setOnItemClickListener(new OnItemClickListener() {
			@Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int position,
                    long arg3) {
					clickGoToRead(arrayList.get(position)) ;
            }
		}) ;
		
		listView.setOnItemLongClickListener(new OnItemLongClickListener() {

			@Override
            public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
                    int arg2, long arg3) {
				showDeleteDialog(arrayList.get(arg2)) ;
	            return false;
            }
		}) ;
		
	}
	
	private void showDeleteDialog(final SearchResultObject object){
		
		Builder builder = new Builder(context) ;
		builder.setTitle("确认删除？")
		.setPositiveButton("确定", new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				CollectionSqlite sqlite = new CollectionSqlite(context) ;
				sqlite.open() ;
				sqlite.deleteData(object) ;
				sqlite.close() ;
				initData() ;
				adapter.notifyDataSetChanged() ;
				showToast("删除成功", false) ;
				
			}
		})
		.setNegativeButton("取消", null)
		.create().show() ;
		
		
		
	}
	
	
	
	
	/**
     * 点击阅读
     * @param clickIndex
     *2012-7-31 下午2:23:08
     */
    private void clickGoToRead(SearchResultObject object ){
    	Intent intent = new Intent() ;
		intent.setClass(context, TextByListActivity.class) ;
		Bundle bundle = new Bundle() ;
		bundle.putSerializable("object", object) ;
		intent.putExtras(bundle) ;
		intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP) ;
		startActivity(intent) ;
//		overridePendingTransition(R.anim.scale_zoom_in, R.anim.normal) ;
    	
    }
	
	private class CollectionAdapter extends BaseAdapter{

		private Pattern pattern;

		@Override
        public int getCount() {
			if (arrayList == null) {
             return 0 ;
            }
			return arrayList.size();
        }

		@Override
        public Object getItem(int position) {
	        // TODO Auto-generated method stub
	        return position;
        }

		@Override
        public long getItemId(int position) {
	        // TODO Auto-generated method stub
	        return position;
        }

		@Override
        public View getView(int position, View convertView, ViewGroup parent) {
			LinearLayout layout = (LinearLayout) layoutInflater.inflate(R.layout.adapter_collection_item_listvew, null) ;
			TextView timeTextView = (TextView) layout.findViewById(R.id.tv_collection_time) ;
			TextView comtentTextView = (TextView) layout.findViewById(R.id.tv_collection_content) ;
//			try {
				SearchResultObject object = arrayList.get(position) ;
				timeTextView.setText("添加时间:" + object.getTimeString()) ;
				String content = object.getContentString() ;
				
				pattern = Pattern.compile(SystemConfig.regex) ;
				Matcher matcher = pattern.matcher(content) ;
				String val = null ;
				String tempString ;
				int len = 0  ;
				if (matcher.find()) {
					val = matcher.group() ;
					len = val.length() ;
					if (position == 0) { //去掉首行多空一格字符
						len++ ;
					}
				}
				tempString = content.substring(len) ; //经文
				String displayString = "<font color=#1111bb>" + object.getBookShortString() + val + "</font>" + tempString ;
				comtentTextView.setText(Html.fromHtml(displayString)) ;
//			}
//            catch (Exception e) {
//            	e.printStackTrace() ;
//            	Utils.sendMail("收藏的getView错误", " ") ;
//            }
			return layout;
        }
		
	}
	
	
}
